var fancybox_width = 934;
var fancybox_height = 500;

$(document).ready(function() {
    loadDatePickers();

    initSetShiftLeader();
    initRemoveMemberFromRole();

    initAdminChangeRole();
    initShiftLeaderChangeRole();

    initAddShiftRole();
    initDeleteShiftRole();

    initCourseMembers();
    initExpertiseTables();

    initAdminMembersTable();
    initAdminUsersTable();
    initAdminEventTable();
    initAdminShiftTable();
    initAdminAccessMemberTable();
    initAdminMembershipFeeTable();

    initCoreEventTable();
    initCoreShiftTable();

    initCoreShiftExchangeTable();
    
    initViewDiploma();

    submitEditShiftForm();
    initPastShiftTable();
});

function initSetShiftLeader() {
    $('table.admin_member_roles').delegate('input.shiftLeaderCheckBox', 'change', function(){
        var shiftRoleId = $(this).attr('value');
        toggleShiftLeader($(this), shiftRoleId);
        return null;
    });
}

function toggleShiftLeader(element, roleId) {
    var elementHtml = element;
    var parent = element.parent();
    parent.html(loadingAnimation);

    $.ajax({
        url: baseurl + '/admin/shift/setisleader',
        type: 'POST',
        data: { format: 'json', role: roleId },
        dataType : 'json',
        success: function(response){
            parent.html(elementHtml);
            if(response.isLeader) {
                element.attr('checked', 'true');
            } else {
                element.removeAttr('checked');
            }
        },
        error: function(){
            alert('ERROR: Update was not successful. Please try again later.');
        }
    });
}

function loadDatePickers()
{
    $.datepicker.regional['no'] = {
    closeText: 'Lukk',
        prevText: '&laquo;Forrige',
    nextText: 'Neste&raquo;',
    currentText: 'I dag',
        monthNames: ['Januar','Februar','Mars','April','Mai','Juni', 'Juli','August','September','Oktober','November','Desember'],
        monthNamesShort: ['Jan','Feb','Mar','Apr','Mai','Jun', 'Jul','Aug','Sep','Okt','Nov','Des'],
    dayNamesShort: ['Søn','Man','Tir','Ons','Tor','Fre','Lør'],
    dayNames: ['Søndag','Mandag','Tirsdag','Onsdag','Torsdag','Fredag','Lørdag'],
    dayNamesMin: ['Sø','Ma','Ti','On','To','Fr','Lø'],
        dateFormat: 'yy-mm-dd', firstDay: 1,
    isRTL: false
    };
    $.datepicker.setDefaults($.datepicker.regional['no']);

     addDatePicker('#appearance_date');
     addDatePicker('#from_date');
     addDatePicker('#to_date');
     addDatePicker('#course_date');
     addDatePicker('#competence_date');

     $("#calendar_from_date").datepicker({
    altField: 'input#from_date',
        dateFormat: 'dd.mm.yy',
        minDate: $(this).datepicker('getDate') || 22,
        maxDate: "+3m",
        onSelect: function(dateText, inst){
            var fromDate = new Date(inst.selectedYear, inst.selectedMonth, inst.selectedDay);
            var toDate = new Date($('#calendar_to_date').datepicker('getDate'));

             if($('#calendar_to_date').datepicker('isDisabled')){
                $('#calendar_to_date').datepicker('enable');
                $('#calendar_to_date').datepicker('setDate', fromDate);
            }

            if (fromDate > toDate) {
                $('#calendar_to_date').datepicker('setDate', fromDate);
            }
        }
    });

    $("#calendar_to_date").datepicker({
    altField: 'input#to_date',
        dateFormat: 'dd.mm.yy',
        minDate: $(this).datepicker('getDate') || 22,
        maxDate: "+3m"
    });
    $("#calendar_to_date").datepicker('disable');
}

function addDatePicker(element) {
    $(element).datepicker({
            dateFormat: 'dd.mm.yy'
    });
}

function initViewDiploma() {
    $(".profile_box.diplomas a.image").fancybox();
    $(".core_user_edit_diplomas a.image").fancybox();
}

function initAddShiftRole() {
    $('#add_shift_role_link').fancybox({
        autoDimensions: false,
        width: fancybox_width,
        height: fancybox_height,
        titleShow: false
    });

    var formElement = $('#shift_role_form');

    $('#shift_role', formElement).dataTable({});

    setSubmitButtonState(formElement, false);
    initAddShiftRoleForm(formElement);
}

function initAddShiftRoleForm(formElement) {
    formElement.submit(function() {
        saveAddShiftRoleForm(formElement);
        $.fancybox.close();
        return false;
    });

    formElement.delegate('input[type=radio]', 'click', function(){
       setSubmitButtonState(formElement, true);
    });
}

function saveAddShiftRoleForm(formElement) {
    var url = formElement.attr('action');
    var postData = formElement.serialize() + '&format=html'

    $.ajax({
        type: 'POST',
        url: url,
        data: postData,
        dataType : 'html',
        success: function(data){
            $("#srtablebody").append(data);
        },
        error: function(){
            alert('ERROR: Update was not successful. Please try again later.');
        }
    });
}

// Submits the edit shift form, clears any previously added error and success messages - and displays new ones for the data submitted.
function submitEditShiftForm() {
    $("#addShiftForm").submit(function(event){
        event.preventDefault();

        $(".message_error").remove();
        $(".message_success").remove();
        $(".errors").remove();

        var loader = $(loadingAnimation);
        $('#submitEditForm').after(loader);

        var shift_id = $('input[name=shift_id]', $(this));
        var name = $('input[name=name]', $(this));
        var appearanceDate = $('input[name=appearance_date]', $(this));
        var appearanceTime = $('#appearance_time-hours').val() + ':' + $('#appearance_time-minutes').val();
        var fromDate = $('input[name=from_date]', $(this));
        var fromTime = $('#from_time-hours').val() + ':' + $('#from_time-minutes').val();
        var toDate = $('input[name=to_date]', $(this));
        var toTime = $('#to_time-hours').val() + ':' + $('#to_time-minutes').val();
        var specialDescription = $('#special_description').val();
        var equipmentList = $('#equipment_list').val();

        var ajaxData = {
            "format" : "json",
            "shift_id" : shift_id.val(),
            "name" : name.val(),
            "appearance_date" : appearanceDate.val(),
            "appearance_time" : appearanceTime,
            "from_date" : fromDate.val(),
            "from_time" : fromTime,
            "to_date" : toDate.val(),
            "to_time" : toTime,
            "special_description" : specialDescription,
            "equipment_list" : equipmentList
        };

        var url = $(this).attr('href');
        $.ajax({
            url  : url,
            type: 'POST',
            cache : false,
            data : ajaxData,
            dataType : 'json',
            success : function(result){
                if(result.status != true){
                     $("#addShiftForm").before("<p class='message_error'>Et eller flere av feltene er ikke riktig utfylt.</p>");
                    for(var i in result.status.name){
                        $("#name").after("<ul class='errors'><li>" + result.status.name[i] + "</li></ul>");
                    }
                    for(var i in result.status.appearance_time){
                        $("#appearance_time-minutes").after("<ul class='errors'><li>" + result.status.appearance_time[i] + "</li></ul>");
                    }
                    for(var i in result.status.appearance_date){
                        $("#appearance_date").after("<ul class='errors'><li>" + result.status.appearance_date[i] + "</li></ul>");
                    }
                    for(var i in result.status.from_time){
                        $("#from_time-minutes").after("<ul class='errors'><li>" + result.status.from_time[i] + "</li></ul>");
                    }
                    for(var i in result.status.from_date){
                        $("#from_date").after("<ul class='errors'><li>" + result.status.from_date[i] + "</li></ul>");
                    }
                    for(var i in result.status.to_time){
                        $("#to_time-minutes").after("<ul class='errors'><li>" + result.status.to_time[i] + "</li></ul>");
                    }
                    for(var i in result.status.to_date){
                        $("#to_date").after("<ul class='errors'><li>" + result.status.to_date[i] + "</li></ul>");
                    }
                    for(var i in result.status.special_description){
                        $("#special_description").after("<ul class='errors'><li>" + result.status.special_description[i] + "</li></ul>");
                    }
                    for(var i in result.status.equipment_list){
                        $("#equipment_list").after("<ul class='errors'><li>" + result.status.equipment_list[i] + "</li></ul>");
                    }
                } else {
                        $("#addShiftForm").before("<p class='message_success'> Vakten er oppdatert. </p>");
                }
                loader.remove();
            }
        });
    });
}

function initAdminChangeRole() {
    $('table.admin_member_roles').delegate('a.member_role_link', 'click', function(event){
        event.preventDefault();
        var url = $(this).attr('href');

        $.fancybox.showActivity();

        $.ajaxSetup({cache: false})
        $.get(url, { format: "html" }, function(data){
            var form = '#memberRoleForm';
            createFancyboxWithDataTable(data);
            setSubmitButtonState(form, false);
            $('#update_member_table', form).removeAttr('disabled');
            initAdminChangeRoleForm($(form));
        });
    });
}

function initAdminChangeRoleForm(formElement) {
    $(this).delegate('#update_member_table', 'submit', function(){
        var url = $(this).attr('action');
        var postData = $(this).serialize() + '&format=html'

        $('input[type=submit]', $(this)).after(loadingAnimation);
        $.ajax({
            type: 'POST',
            url: url,
            data: postData,
            dataType : 'html',
            success: function(data){
                $('.lightbox').replaceWith(data);
                $('#datatable').dataTable({
                    bProcessing: true,
                    bSort: true,
                    sPaginationType: "full_numbers",
                    aaSorting: []
                });
            },
            error: function(){
                alert('ERROR: Update was not successful. Please try again later.');
            }
        });
        return false;
    });

    formElement.delegate('input[type=radio]', 'click', function(){
       setSubmitButtonState(formElement, true);
    });

    $('#memberRoleForm input[type=submit]').click(function (event) {
            event.preventDefault();
            $('#memberRoleForm').submit();
    });

    $(this).delegate('#memberRoleForm', 'submit', function(event) {
        event.preventDefault();

        var url = $(this).attr('action');
        var postData = $(this).serialize() + '&format=json'

        var loader = $(loadingAnimation).css('margin-top', '10px');
        $('input[type=submit]', $(this)).after(loader);
        $.ajax({
            type: 'POST',
            url: url,
            data: postData,
            dataType : 'json',
            success: function(data){
                updateRoleTable(data, true);
                $.fancybox.close();
            },
            error: function(){
                alert('ERROR: Update was not successful. Please try again later.');
            }
        });
        return false;
    });
}

function initShiftLeaderChangeRole() {
    $('table.admin_member_roles').delegate('a.leader_change_role', 'click', function(event){
        event.preventDefault();
        var url = $(this).attr('href');

        $.fancybox.showActivity();

        $.ajaxSetup({cache: false})
        $.get(url, { format: "html" }, function(data){
            var formSelector = '#memberRoleForm';
            createFancyboxWithDataTable(data);
            setSubmitButtonState(formSelector, false);
            initForm(formSelector);
        });
    });
}

function createFancyboxWithDataTable(data) {
    $.fancybox(data);
    $('#fancybox-inner').width(fancybox_width);
    $('#fancybox-wrap').width(fancybox_width+20);
    $('#fancybox-inner').height(fancybox_height);
    $('#fancybox-wrap').height(fancybox_height+20);

    $.fancybox.center();

    $('#datatable').dataTable({
        bProcessing: true,
        bSort: true,
        sPaginationType: "full_numbers",
        aaSorting: []
    });
}

function setSubmitButtonState(form, state) {
    var button = $('input[type=submit]', form);
    if(!state) {
        button.attr('disabled', 'disabled');
    } else {
        button.removeAttr('disabled');
    }
}

function initForm(form) {
    var formElement = $(form);
    formElement.submit(function() {
        saveForm(formElement);
        $.fancybox.close();
        return false;
    });

    formElement.delegate('input[type=radio]', 'click', function(){
       setSubmitButtonState(form, true);
    });
}

function saveForm(formElement) {
    var url = formElement.attr('action');
    var postData = formElement.serialize() + '&format=json'

    $.ajax({
        type: 'POST',
        url: url,
        data: postData,
        dataType : 'json',
        success: function(data){
            updateRoleTable(data);
        },
        error: function(){
            alert('ERROR: Update was not successful. Please try again later.');
        }
    });
}

function updateRoleTable(data, showDeleteLink) {
    var tableCell = data.last_name + ', ' + data.first_name;
    tableCell += showDeleteLink == true ? ' <a class="removeMemberLink" href="' + baseurl + '/admin/shift/removememberfromrole/role/' + data.sr_id + '" alt="Fjern person fra rolle" title="Fjern person fra rolle"><img src="'+ imgurl +'images/icons/cross.png"></a>' : '';
    $('#cell-' + data.sr_id, 'table.admin_member_roles').html(tableCell);
}

function initRemoveMemberFromRole() {
    $('.admin_member_roles').delegate('.removeMemberLink', 'click', function(event){
        event.preventDefault();

        var url = $(this).attr('href');
        var parent = $(this).parent();

        $(this).replaceWith(loadingAnimation);

        $.ajax({
            url: url,
            type: 'GET',
            data: { format: 'json' },
            dataType: 'json',
            cache: false,
            success: function(response){
                parent.html('');
            },
            error: function(){
                alert('ERROR: Update was not successful. Please try again later.');
            }
        });
    });
}

function initDeleteShiftRole() {
    $('.admin_member_roles').delegate('.remove_role_link', 'click', function(event){
        event.preventDefault();
        var element = $(this);
        var $dialog = $('<div></div>')
    .html('Er du sikker på at du vil slette denne rollen?')
    .dialog({
      autoOpen: false,
      title: 'Slett rolle',
            buttons: {
                'Slett rolle' : function() {
                    deleteShiftRole(element);
                    $(this).dialog('close');
                },
                'Avbryt': function(){
                    $(this).dialog('close');
                }
            }
    });

    $dialog.dialog('open');



    });
}

function deleteShiftRole(element){
        var url = element.attr('href');
        var parentTr = element.closest('tr');

        element.replaceWith(loadingAnimation);

        $.ajax({
            url: url,
            type: 'GET',
            data: { format: 'json' },
            dataType: 'json',
            cache: false,
            success: function(response){
                parentTr.slideUp('slow', function() {element.remove();});
            },
            error: function(){
                alert('ERROR: Update was not successful. Please try again later.');
            }
        });
}


function initAdminMembershipFeeTable() {
    $('form#add_payment_to_members').submit(function() {
        console.log('woo');
        var sData = $('input', membershipFeeTable.fnGetNodes());
        for (var i = 0; i < sData.length; i++) {
            var id = $(sData[i]).attr('id');
            if ($(this).find('#'+id).length == 0) {
                // element does not exist inside the form,
                // so let's append it to the form!
                $(this).append($(sData).attr('style', 'display: none'));
            }
        }

        return true;
    });

    membershipFeeTable = $('#membership_fee_members').dataTable({
        "iDisplayLength": 25,
        "aLengthMenu": [[10, 25, 50, 100, -1], [10, 25, 50, 100, "Alle"]],
        "aaSorting": [[2, 'desc']],
        "aoColumnDefs": [
            { "sWidth": "15px", "aTargets": [ 0 ] },
            { "sType": "date-euro", "aTargets": [ 2 ] }
        ]
    });
}


function initAdminAccessMemberTable() {
    $('form#edit_room_access_to_members').submit(function() {
        var sData = $('input', accessMemberTable.fnGetNodes());
        for (var i = 0; i < sData.length; i++) {
            var id = $(sData[i]).attr('id');
            if ($(this).find('#'+id).length == 0) {
                // element does not exist inside the form,
                // so let's append it to the form!
                $(this).append($(sData).attr('style', 'display: none'));
            }
        }

        return true;
    });

    accessMemberTable = $('#roomaccess_members').dataTable({
        "iDisplayLength": 25,
        "aLengthMenu": [[10, 25, 50, 100, -1], [10, 25, 50, 100, "Alle"]],
        "aaSorting": [[1, 'asc']],
        "aoColumnDefs": [
            { "sWidth": "15px", "aTargets": [ 0 ] }
        ]
    });
}

function initCourseMembers() {
    $('form#add_course_to_members').submit(function() {
        var sData = $('input', courseMembersTable.fnGetNodes());
        for (var i = 0; i < sData.length; i++) {
            var id = $(sData[i]).attr('id');
            if ($(this).find('#'+id).length == 0) {
                // element does not exist inside the form,
                // so let's append it to the form!
                $(this).append($(sData).attr('style', 'display: none'));
            }
        }

        return true;
    });

    courseMembersTable = $('#course_members').dataTable({
        "iDisplayLength": 25,
        "aLengthMenu": [[10, 25, 50, 100, -1], [10, 25, 50, 100, "Alle"]],
        "aaSorting": [[2, 'asc']],
        "aoColumnDefs": [
            { "sWidth": "15px", "aTargets": [ 0 ] },
            { "sType": "date-euro", "aTargets": [ 2 ] }
        ]
    });
}

function initPastShiftTable() {
    // TODO: Enable this one???
    /*$('.last_shifts table').dataTable({
        "iDisplayLength": 10,
        "aLengthMenu": [[10, 25, 50, 100, -1], [10, 25, 50, 100, "Alle"]],
        "aaSorting": [[0, "asc"]],
    });*/
}

function initExpertiseTables() {
    $('#courses').dataTable({
        "iDisplayLength": 10,
        "aLengthMenu": [[10, 25, 50, 100, -1], [10, 25, 50, 100, "Alle"]],
        "aaSorting": [[0, "asc"]],
    });

    $('#competences').dataTable({
        "iDisplayLength": 10,
        "aLengthMenu": [[10, 25, 50, 100, -1], [10, 25, 50, 100, "Alle"]],
        "aaSorting": [[0, "asc"]],
    });
}

function initAdminMembersTable() {
    $('table.admin_member').dataTable({
        "iDisplayLength": 25,
        "aLengthMenu": [[10, 25, 50, 100, -1], [10, 25, 50, 100, "Alle"]],
        "aaSorting": [[0, "asc"]],
    });
}

function initAdminUsersTable() {
    $('table.admin_users').dataTable({
        "iDisplayLength": 25,
        "aLengthMenu": [[10, 25, 50, 100, -1], [10, 25, 50, 100, "Alle"]],
        "aaSorting": [[0, "asc"]],
        "aoColumnDefs": [
            { "sWidth": "15px", "aTargets": [ 4 ] },
            { "bSearchable": false, "aTargets": [ 3, 4 ]},
            { "bSortable": false, "aTargets": [ 2, 3, 4 ]}
        ]
    });
}

function initAdminEventTable() {
    $('table.admin_events').dataTable({
        "iDisplayLength": 25,
        "aLengthMenu": [[10, 25, 50, 100, -1], [10, 25, 50, 100, "Alle"]],
        "aaSorting": [[2, "asc"]],
        "aoColumnDefs": [
            { "sWidth": "33px", "aTargets": [ 4 ] },
            { "bSearchable": false, "aTargets": [ 4 ] },
            { "bSortable": false, "aTargets": [ 4 ] },
            { "sType": "date-euro", "aTargets": [ 2, 3 ] }
        ]
    });
}

function initAdminShiftTable() {
    $('table.admin_shifts').dataTable({
        "iDisplayLength": 25,
        "aLengthMenu": [[10, 25, 50, 100, -1], [10, 25, 50, 100, "Alle"]],
        "aaSorting": [[2, "asc"]],
        "aoColumnDefs": [
            { "sWidth": "53px", "aTargets": [ 4 ] },
            { "bSearchable": false, "aTargets": [ 4 ] },
            { "bSortable": false, "aTargets": [ 4 ] },
            { "sType": "date-euro", "aTargets": [ 2, 3 ] }
        ]
    });
}

function initCoreEventTable() {
    $('table.core_events').dataTable({
        "iDisplayLength": 25,
        "aLengthMenu": [[10, 25, 50, 100, -1], [10, 25, 50, 100, "Alle"]],
        "aaSorting": [[3, "asc"]],
        "bFilter": true,
        "bLengthChange": true,
        "aoColumnDefs": [
            { "sType": "date-euro", "aTargets": [ 3, 4 ] }
        ]
    });
}


function initCoreShiftTable() {
    $('table.core_shifts').dataTable({
        "iDisplayLength": 25,
        "aLengthMenu": [[10, 25, 50, 100, -1], [10, 25, 50, 100, "Alle"]],
        "aaSorting": [[1, "asc"]],
        "bFilter": false,
        "bLengthChange": false,
        "aoColumnDefs": [
            { "bSearchable": false, "aTargets": [ 3 ] },
            { "bSortable":   false, "aTargets": [ 3 ] },
            { "sType": "date-euro", "aTargets": [ 2 ] }
        ]
    });
}

function initCoreShiftExchangeTable() {
    $('table.exchange_members').dataTable({
        "iDisplayLength": 25,
        "aLengthMenu": [[10, 25, 50, 100, -1], [10, 25, 50, 100, "Alle"]],
        "aaSorting": [[2, "asc"]],
        "bFilter": true,
        "bLengthChange": true,
        "aoColumnDefs": [
            { "bSearchable": false, "aTargets": [ 0, 2 ] },
            { "bSortable":   false, "aTargets": [ 0 ] },
            { "sWidth": "15px", "aTargets": [ 0 ] }
        ]
    });
}
